/*
 * File Name：UploadBigFile.java
 * Copyright：Copyright 2008-2013 CiWong.Inc. All Rights Reserved.
 * Description： UploadBigFile.java
 * Modify By：RES-KUNZHU
 * Modify Date：2013-3-26
 * Modify Type：Add
 */
package com.ciwong.libs.utils.volley;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ciwong.libs.utils.AsyncHttpRequest;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWResource;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 上传大文件类
 * <p>
 * <pre>
 * </pre>
 *
 * @author RES-KUNZHU
 * @version ciwong v.1.0 2013-3-26
 * @since ciwong v.1.0
 */
public class AsyncUploadLargeFile {
    /**
     * 鹏校通注册用户名已经存在
     */
    public static final int CODE_USER_EXITS = 409;
    /**
     * 返回文件信息
     */
    public static final int RESULT_TYPE_FILEINFO = 1;

    /**
     * 返回字符串
     */
    public static final int RESULT_TYPE_STRING = 2;

    /**
     * 返回指定对象
     */
    public static final int RESULT_TYPE_OBJ = 3;

    /**
     * action
     */
    private static HttpRequest.UploadFileAction action;

    private boolean isPost = false;

    /**
     * 请求头
     */
    private Map<String, String> header;

    /**
     * 重试次数
     */
    private static final int RETRY_TIME = 2;

    private static final String TAG = "UploadLargeFile";

    /**
     * handler标示，更新进度
     */
    private static final int HANDLER_FLAG_UPDATE_PROGRESS = 0;

    /**
     * handler标示，上传完毕
     */
    private static final int HANDLER_FLAG_COMPLETE_UPLOAD = 1;

    /**
     * 出现异常
     */
    private static final int HANDLER_FLAG_ERROR_UPLOAD = 2;

    /**
     * 重试
     */
    private static final int HANDLER_FLAG_RETRY = 3;

    /***
     * 换行符
     */
    private static final String LINE_END = "\r\n";

    /**
     * 两个横线
     */
    private static final String TWO_HYPHEN = "--";

    /**
     * 边界符
     */
    private String BOUNDARY = "-----------------------------";

    /**
     * activity
     */
    private Context mContext;

    /**
     * 需要上传的文件的路径
     */
    private String[] filePaths;

    /**
     * 参数
     */
    private Map<String, String> params;

    /**
     * 上传地址
     */
    private String urlAction;

    /**
     * 是否显示进度条
     */
    private boolean showProgressBar;

    /**
     * 进度条
     */
    private ProgressBar progressBar;

    /**
     * 弹出框
     */
    private CWDialog progressDialog;

    /**
     * 总大小
     */
    private TextView tvTotalSize;

    /**
     * 已上传大小
     */
    private TextView tvTranseredSize;

    /**
     * 连接
     */
    private HttpURLConnection connection;

    /**
     * 输出流
     */
    private DataOutputStream outputStream;

    /**
     * 请求体总大小
     */
    private int totalSize;

    /**
     * 已上传总大小
     */
    private int totalTransfered;

    /**
     * 错误类型
     */
    private int errorType;

    /**
     * 回调函数
     */
    private UploadFileCallback callBack;

    /**
     * 读取超时时间
     */
    private int readTimeOut = 15000;

    /**
     * 上传线程
     */
    private Thread uploadThread;

    private boolean stoped = false;

    private int retried = 0;

    private boolean vertify;

    private int resultType = RESULT_TYPE_FILEINFO;

    private Class clazz;

    private String resultMsg;

    private int code;

    private boolean isTFSServer;

    private InputStream inputstream;

    /**
     * handler
     */
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case HANDLER_FLAG_UPDATE_PROGRESS:

                    if (progressDialog != null && progressDialog.isShowing()) {
                        DecimalFormat df = new DecimalFormat("#.00");
                        progressBar.setMax(msg.arg1);
                        progressBar.setProgress(msg.arg2);
                        tvTotalSize.setText(df.format((float) msg.arg1 / 1024 / 1024) + " MB");

                        tvTranseredSize.setText(df.format((float) msg.arg2 * 100 / (float) msg.arg1) + "%");
                    }
                    callBack.updateProgress(totalTransfered, totalSize);
                    break;
                case HANDLER_FLAG_COMPLETE_UPLOAD:
                    dismissDialog();
                    if (resultType == RESULT_TYPE_OBJ) {
                        callBack.uploadCompleted(code, msg.obj, resultMsg);
                    } else {
                        callBack.updateCompleted(msg.obj);
                    }
                    break;
                case HANDLER_FLAG_ERROR_UPLOAD:
                    handlerException((Exception) msg.obj);
                    break;
                case HANDLER_FLAG_RETRY:
                    executeUpload();
                    break;
            }
        }

        ;
    };

    /**
     * Cnstructor Method。
     *
     * @param filePath 文件路径
     * @param params   参数
     * @param url      url
     */
    public AsyncUploadLargeFile(String[] filePath, Map<String, String> params, String url, UploadFileCallback callback) {
        this(null, filePath, params, url, callback, false);
    }

    /**
     * Cnstructor Method。
     *
     * @param context  activity
     * @param filePath 文件路径
     * @param params   参数
     * @param url      url
     */
    public AsyncUploadLargeFile(Activity context, String[] filePath, Map<String, String> params, String url,
                                UploadFileCallback callback) {
        this(context, filePath, params, url, callback, false);
    }

    /**
     * Cnstructor Method。
     *
     * @param stream   输入流
     * @param url      地址
     * @param callback 回调
     */
    public AsyncUploadLargeFile(InputStream stream, String url, UploadFileCallback callback) {
        this(null, null, null, url, callback, false);
        this.inputstream = stream;
    }

    /**
     * Cnstructor Method。
     *
     * @param context      activity
     * @param filePath     文件路径
     * @param params       参数
     * @param showProgress 是否显示进度条
     */
    public AsyncUploadLargeFile(Activity context, String[] filePath, Map<String, String> params, String url,
                                UploadFileCallback callback, boolean showProgress) {
        this.mContext = context;
        this.filePaths = filePath;
        this.params = params;
        this.showProgressBar = showProgress;
        this.urlAction = url;
        this.callBack = callback;
        init();
    }

    private void setToken() {
        BaseRequest.VerifyInfo mVerifyInfo = BaseRequest.getVerifyInfo();
        if (mVerifyInfo != null) {
            if (urlAction.indexOf("?") != -1) {
                urlAction += "&";
            } else {
                urlAction += "?";
            }
            urlAction += HttpHelper.getVerifyStr(mVerifyInfo);
        }
    }

    /**
     * 设置请求头
     *
     * @param header 请求头
     */
    public void setHeader(Map<String, String> header) {
        this.header = header;
    }

    /**
     * 开始上传
     */
    public void executeUpload() {
        errorType = -1;
        if (!NetworkUtils.isOnline()) {
            errorType = AsyncHttpRequest.REQUEST_ERROR_NET_UNCONNECT;
            toastError();
            return;
        }
        if (vertify) {
            setToken();
        }
        showDialog();
        uploadThread = new Thread(new Runnable() {
            public void run() {
                try {
                    initUrlConnection();
                    if (errorType != -1) {
                        return;
                    }
                    writeParams();
                    if (filePaths != null) {
                        for (String filePath : filePaths) {
                            if (!stoped)
                                sendFileToServer(new FileInputStream(filePath), getFileName(filePath));
                        }
                    } else if (inputstream != null) {
                        if (!stoped)
                            sendFileToServer(inputstream, null);
                    }
                    CWLog.d("debug",
                            "size:"
                                    + (outputStream.size() + (TWO_HYPHEN + BOUNDARY + TWO_HYPHEN + LINE_END).getBytes().length));
                    if (!isTFSServer) {
                        outputStream.writeBytes(TWO_HYPHEN + BOUNDARY + TWO_HYPHEN + LINE_END);
                    }
                    outputStream.flush();
                    outputStream.close();
                    outputStream = null;
                    completeUpload();
                } catch (Exception e) {
                    if (e instanceof SocketTimeoutException && retried < RETRY_TIME) {
                        retried++;
                        CWLog.d(TAG, "RETRY:" + retried);
                        Message msg = mHandler.obtainMessage(HANDLER_FLAG_RETRY);
                        msg.sendToTarget();
                    } else {
                        e.printStackTrace();
                        Message msg = mHandler.obtainMessage(HANDLER_FLAG_ERROR_UPLOAD);
                        msg.obj = e;
                        msg.sendToTarget();
                    }
                }
            }
        });
        uploadThread.start();
    }

    /**
     * 启用token
     */
    public void enbaleVertify() {
        vertify = true;
    }

    /**
     * 设置是否是tfs服务器
     *
     * @param isTFS
     */
    public void setIsTFSServer(boolean isTFS) {
        isTFSServer = isTFS;
    }

    /**
     * 设置请求地址
     *
     * @param url 请求地址
     */
    public void setUrl(String url) {
        urlAction = url;
    }

    /**
     * 设置上传文件回调
     *
     * @param cb
     */
    public void setCallback(UploadFileCallback cb) {
        this.callBack = cb;
    }

    public String getLocalPath() {
        return filePaths[0];
    }

    /**
     * 设置返回类型
     *
     * @param type
     */
    public void setResultType(int type) {
        this.resultType = type;
    }

    /**
     * 设置返回对象的类
     *
     * @param clazz
     */
    public void setResultClazz(Class clazz) {
        this.clazz = clazz;
    }

    /**
     * 取消上传
     */
    public void cancelUpload() {
        CWLog.d(TAG, "cancelUpload");
        if (uploadThread != null && uploadThread.isAlive()) {
            stoped = true;
            dismissDialog();
        }
    }

    /**
     * 设置action
     *
     * @param act action
     */
    public static void setAction(HttpRequest.UploadFileAction act) {
        action = act;
    }

    public void isPost(boolean post) {
        this.isPost = post;
    }

    /**
     * 初始化
     */
    private void init() {
        if (showProgressBar && mContext != null) {
            progressDialog = new CWDialog(mContext);
            View root = LayoutInflater.from(mContext).inflate(CWResource.getLayout("layout.update_download"), null);
            progressBar = (ProgressBar) root.findViewById(CWResource.getId("downloadProgress"));
            tvTranseredSize = (TextView) root.findViewById(CWResource.getId("downloadPercent"));
            tvTotalSize = (TextView) root.findViewById(CWResource.getId("downloadAppSize"));
            progressDialog.setContentView(root);
        }
        BOUNDARY += new Date().getTime();
        // urlAction = "http://192.168.1.232:80?name"
        // urlAction = action.getActionUrl(urlAction);
        // filePaths = new String[]{"/mnt/sdcard/a.apk"};
        // urlAction = "http://192.168.1.88:8888/appstore/upload";
        // urlAction =
        // "http://appstore.ciwong.com:7080/patbypatServer/UrlTest1";
        // urlAction = "http://192.168.1.168:9999/patbypatServer/UrlTest1";
        // urlAction = "http://192.168.1.210:8888/patbypatServer/UrlTest1";
    }

    /**
     * 初始化urlconnection
     *
     * @throws Exception 异常
     */
    private void initUrlConnection() throws Exception {

        CWLog.d(TAG, "url:" + urlAction);
        URL url = new URL(urlAction);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        // connection.setReadTimeout(readTimeOut);
        // connection.setConnectTimeout(6000);
        // connection.setRequestProperty("HOST",
        // url.getHost()+":"+url.getPort());
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0");
        connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
        connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        // connection.setRequestProperty("Connection", "Keep-Alive");
        if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
            connection.setRequestProperty("Connection", "close");
        } else {
            connection.setRequestProperty("Connection", "Keep-Alive");
        }
        if (isPost) {
            connection.setRequestProperty("content-type", "text/html");
        } else {
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        }
        connection.setFixedLengthStreamingMode(getTotalSizeOfBody());
        if (header != null && !header.isEmpty()) {
            Set<String> keys = header.keySet();
            Iterator<String> ki = keys.iterator();
            while (ki.hasNext()) {
                String key = ki.next();
                connection.setRequestProperty(key, header.get(key));
            }
        }
        // connection.setChunkedStreamingMode(1024);
        // connection.
        outputStream = new DataOutputStream(connection.getOutputStream());
        CWLog.d(TAG, "URL:" + url);
    }

    /**
     * 获取请求体总大小
     *
     * @return 请求体总大小
     * @throws Exception 异常
     */
    private int getTotalSizeOfBody() throws Exception {
        totalSize = 0;
        if (inputstream != null) {
            return inputstream.available();
        }
        // 计算文件大小
        if (filePaths != null) {
            for (String path : filePaths) {
                File file = new File(path);
                if (!file.exists()) {
                    callBack.error(AsyncHttpRequest.REQUEST_ERROR_FILE);
                    break;
                }
                FileInputStream fileInputStream = new FileInputStream(file);
                String connstr = null;
                connstr = getContentStr(getFileName(path));
                totalSize += fileInputStream.available();
                if (!isTFSServer) {
                    totalSize += connstr.getBytes("utf-8").length + LINE_END.getBytes("utf-8").length * 2
                            + (TWO_HYPHEN + BOUNDARY + LINE_END).getBytes().length;
                }
                // 注：大小加2是与DataOutputStream的writeUTF写入之后的大小匹配
                fileInputStream.close();
            }
            if (!isTFSServer) {
                totalSize += (TWO_HYPHEN + BOUNDARY + TWO_HYPHEN + LINE_END).getBytes("utf-8").length;
            }
        }
        // 计算参数大小
        if (params != null) {
            Set<String> keys = params.keySet();
            for (String str : keys) {
                String value = params.get(str);
                totalSize += (getParamStr(str, value)).getBytes().length;
            }
        }
        updateProgress(0, totalSize);
        // CWLog.d(TAG, "TOTAL_SIZE:" + totalSize);
        CWLog.d("debug", "TOTAL_SIZE:" + totalSize);
        return totalSize;
    }

    /**
     * 写入参数
     *
     * @throws Exception 异常
     */
    private void writeParams() throws Exception {
        if (params != null) {
            Set<String> keys = params.keySet();
            for (String str : keys) {
                String value = params.get(str);
                String lastStr = getParamStr(str, value);
                outputStream.writeBytes(lastStr);
                totalTransfered += lastStr.getBytes("utf-8").length;
            }
        }
    }

    /**
     * 拼接参数串
     *
     * @param key   键
     * @param value 值
     * @return 串
     */
    private String getParamStr(String key, String value) {
        String paramStr = "";
        try {
            paramStr = TWO_HYPHEN + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\"" + key + "\""
                    + LINE_END + LINE_END + value + LINE_END;
            CWLog.d(TAG, "PARAMSTR:" + paramStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return paramStr;

    }

    /**
     * 获取文件名
     *
     * @param filePath 文件路径
     * @return 文件名
     */
    private String getFileName(String filePath) {
        String name = filePath.substring(filePath.lastIndexOf("/") + 1);
        return name;
    }

    /**
     * 构建上传文件描述
     *
     * @param name 文件名
     * @return 文件描述
     */
    private String getContentStr(String name) {
        String rs = "Content-Disposition: form-data; name=\"file\";filename=\"" + name + "\"" + LINE_END;
        rs += "Content-Type: multipart/form-data" + LINE_END;
        return rs;
    }

    /**
     * 写入文件
     *
     * @param fileName 文件名称
     * @return
     */
    private void sendFileToServer(InputStream inputStream, String fileName) throws Exception {
        setCurFileName(fileName);
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        // 打开文件
        InputStream fileInputStream = inputStream;
        if (!isTFSServer) {
            String connstr = null;
            connstr = getContentStr(fileName);
            // CWLog.d("debug", "connstr2:" + connstr.getBytes().length);
            // 写入分隔符，文件名，换行
            outputStream.writeBytes(TWO_HYPHEN + BOUNDARY + LINE_END);
            // CWLog.d("debug", "size1:" + outputStream.size());
            outputStream.write(connstr.getBytes("utf-8"));
            // CWLog.d("debug", "size2:" + outputStream.size());
            outputStream.writeBytes(LINE_END);
        }

        // 写入文件
        int fileSize = bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        int transfered = bytesRead;
        totalTransfered += transfered;
        CWLog.d(TAG, "FILE_SIEZ:" + bytesAvailable);
        while (bytesRead > 0 && !stoped) {
            outputStream.write(buffer, 0, bufferSize);
            // outputStream.flush();
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            transfered += bytesRead;
            totalTransfered += bytesRead;
            updateProgress(transfered, fileSize);
            CWLog.i(TAG, totalTransfered + "");

        }
        if (!isTFSServer) {
            outputStream.writeBytes(LINE_END);
        }
        fileInputStream.close();
    }

    /**
     * 更新进度
     *
     * @param transfered 上传大小
     */
    private void updateProgress(int transfered, int fileSize) {
        Message msg = mHandler.obtainMessage(HANDLER_FLAG_UPDATE_PROGRESS);
        msg.arg1 = fileSize;
        msg.arg2 = transfered;
        msg.sendToTarget();
    }

    /**
     * 完成上传
     */
    private void completeUpload() throws Exception {
        if (!stoped) {
            getResponse();
        }
    }

    /**
     * 处理响应
     *
     * @throws Exception
     */
    private void getResponse() throws Exception {
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();
        CWLog.d(TAG, "response->url:" + urlAction + "responseCode:" + serverResponseCode);
        CWLog.d(TAG, "response->MESSAGE:" + serverResponseMessage);

        if (serverResponseCode >= 200 && serverResponseCode < 300) {
            // updateProgress(totalSize,totalSize);
            writeResponse(connection.getInputStream());
        } else if (serverResponseCode == 500) {
            throw new UploadException(UploadException.UPLOADEXCEPTION_EXCEPTION_CODE_SERVER);
        } else if (serverResponseCode == 409) {
            throw new UserNameExistException();
        } else {
            throw new Exception();
        }
    }

    /**
     * 打印响应体
     *
     * @param in 流
     */
    private void writeResponse(InputStream in) throws Exception {
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String str = br.readLine();
        Object obj = null;
        while (str != null) {
            CWLog.d(TAG, "responsebody:" + str);
            sb.append(str);
            str = br.readLine();
        }
        in.close();
        if (resultType == RESULT_TYPE_FILEINFO) {

            Gson mGson = new Gson();
            Type t = new TypeToken<List<BaseRequest.AttachmentUpload>>() {
            }.getType();
            String json = sb.toString();
            CWLog.d("debug", "上传附件结果:" + json);

            json = json.replace("\"", "\\\"").replace("'", "\"").replace("result:", "\"result\":")
                    .replace("msg:", "\"msg\":");
            json = json.replace("}{", "},{");
            CWLog.d("debug", "上传附件结果111:" + json);

            List<BaseRequest.AttachmentUpload> uploads = mGson.fromJson("[" + json + "]", t);
            obj = uploads;
        } else if (resultType == RESULT_TYPE_STRING) {
            obj = sb.toString();
        } else if (resultType == RESULT_TYPE_OBJ) {
            if (clazz != null) {
                try {
                    Gson mGson = new Gson();
                    JSONObject jsonObject = new JSONObject(sb.toString());
                    if (jsonObject.has("data")) {
                        String dataJson = jsonObject.getString("data");
                        if (dataJson != null && !"".equals(dataJson)) {
                            if (clazz != null) {
                                obj = mGson.fromJson(dataJson, clazz);
                            }
                        }
                    }
                    code = jsonObject.getInt("ret");
                    resultMsg = jsonObject.getString("msg");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        Message msg = mHandler.obtainMessage(HANDLER_FLAG_COMPLETE_UPLOAD);
        msg.obj = obj;
        msg.sendToTarget();

    }

    /**
     * 显示进度条
     */
    private void showDialog() {
        if (showProgressBar && !progressDialog.isShowing()) {
            progressDialog.show();
            progressDialog.setCancelable(false);
            progressDialog.setTitle("准备中...");
            progressDialog.setPositiveButton("取消上传", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelUpload();
                }
            });
        }
    }

    /**
     * 设置当前正在上传文件的名字
     *
     * @param fileName
     */
    private void setCurFileName(final String fileName) {
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (progressDialog != null) {
                    progressDialog.setTitle("正在上传  " + fileName);
                }
            }
        });
    }

    /**
     * 隐藏进度条
     */
    private void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    /**
     * 处理异常
     *
     * @param e 异常
     */
    private void handlerException(Exception e) {
        if (stoped) {
            return;
        }
        dismissDialog();
        if (e instanceof java.net.ConnectException || e instanceof java.net.SocketTimeoutException
                || e instanceof EOFException) {
            this.errorType = AsyncHttpRequest.REQUEST_ERROR_TIME_OUT;
        } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
            this.errorType = AsyncHttpRequest.REQUEST_ERROR_SSL;
        } else if (e instanceof IllegalStateException) {
            this.errorType = AsyncHttpRequest.REQUEST_ERROR_URL;
        } else if (e instanceof UserNameExistException) {
            this.errorType = CODE_USER_EXITS;
        } else if (e instanceof UploadException) {
            UploadException ue = (UploadException) e;
            if (ue.getExceptionCode() == UploadException.UPLOADEXCEPTION_EXCEPTION_CODE_SERVER) {
                this.errorType = AsyncHttpRequest.REQUEST_ERROR_500;
                action.changeUploadServer();
            }
        } else {
            this.errorType = AsyncHttpRequest.REQUEST_ERROR_EXCEPTION;
        }
        toastError();
    }

    /**
     * 提示错误
     */
    private void toastError() {
        if (mContext != null) {
            String err = AsyncHttpRequest.getErrorTipRsId(errorType, mContext);
            if (err != null) {
                Toast.makeText(mContext, err, Toast.LENGTH_SHORT).show();
            }
        }
        callBack.error(errorType);
    }

    public static class UploadException extends Exception {
        /**
         *
         */
        private static final long serialVersionUID = -3874803301487505278L;

        /**
         * 服务器异常
         */
        public static int UPLOADEXCEPTION_EXCEPTION_CODE_SERVER = 0;

        /**
         * 异常码
         */
        private int exceptionCode;

        /**
         * Cnstructor Method。
         *
         * @param code 异常码
         */
        public UploadException(int code) {
            super();
            this.exceptionCode = code;
        }

        /**
         * Cnstructor Method。
         *
         * @param msg 异常信息
         */
        public UploadException(String msg) {
            super(msg);
        }

        public int getExceptionCode() {
            return exceptionCode;
        }

        public void setExceptionCode(int exceptionCode) {
            this.exceptionCode = exceptionCode;
        }

    }

    private class UserNameExistException extends Exception {

    }

    /**
     * 回调接口
     *
     * @author RES-KUNZHU
     */
    public static abstract class UploadFileCallback {
        /**
         * 更新进度
         *
         * @param transfered 已上传大小
         * @param total      总大小
         */
        public void updateProgress(int transfered, int total) {
        }

        /**
         * 上传完成
         */
        public void updateCompleted(Object obj) {
        }

        /**
         * 发生异常
         *
         * @param errorCode 异常码
         */
        public void error(int errorCode) {
        }

        /**
         * 上传完成
         *
         * @param resultCode
         * @param data
         * @param msg
         */
        public void uploadCompleted(int resultCode, Object data, String msg) {

        }

    }

}
